<template>
  <div class="dictionaryCost h100">
    <div class="PageContent">
        <el-col :span="4" class="left-tree">
          <el-tree :data="treeData" ref="roleMngTree"
                   :props="defaultProps"
                   node-key="id"
                   default-expand-all
                   check-strictly
                   highlight-current
                   @node-click="handleClick">

          </el-tree>
        </el-col>
        <el-col :span="20"  class="right-tree">
          <el-row style="text-align: left;line-height: 5em;">
            <el-button type="primary" v-if="btnRight.btnRoleMngRefresh" >刷新</el-button>
            <el-button type="primary"  v-if="btnRight.btnRoleMngAdd" @click="add()" >添加</el-button>
            <el-button type="primary"  v-if="btnRight.btnRoleMngEdit" @click="modify()">修改</el-button>
            <el-button type="danger"  v-if="btnRight.btnRoleMngDelete" @click="remove()">删除</el-button>
          </el-row>
          <el-row   class="word-v-middle">

            <el-form :model="searchData" v-if="searchData" class="saveform" ref="organizationdialog" :inline="true" label-width="80px" :disabled="saveFlag">
              <el-row :gutter="5">
                <el-form-item label="角色名称:">
                  <el-input v-model="searchData.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色分类:">
                  <el-select v-model="searchData.roleTypeCode" placeholder="请选择" >
                    <el-option label="全部" value="-1"></el-option>
                    <el-option v-if="saveData.dicts.role_type" v-for="item in saveData.dicts.role_type"
                               :key="item.dataCode"
                               :label="item.dataText"
                               :value="item.dataCode"
                               :disabled="item.disableState?true:false"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="状态:">
                  <el-select v-model="searchData.disableState" onkeydown="return (event.keyCode!=8)" placeholder="请选择" >
                    <el-option label="全部" value="-1"></el-option>
                    <el-option
                      v-for="item in disableState"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                </el-form-item>
                <el-button type="primary" v-if="btnRight.btnRoleMngSearch"  @click="search()">查询</el-button>
              </el-row>
            </el-form>
          </el-row>
          <el-table
            ref="roleTable"
            :data="tableData" :header-cell-style="{background:'rgb(222,225,230)',color:'#606266'}"
            row-key="id"
            border
            default-expand-all
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            @row-click="handleRowClick"
            @select="select" @select-all="selectAll"
            class="tablestyle">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              property="roleCode"
              label="角色编码"
              align = 'center'>
            </el-table-column>
            <el-table-column
              property="roleName"
              label="角色名称"
              align = 'center'
              width="300">
            </el-table-column>
            <el-table-column
              property="roleType"
              label="角色分类"
              align = 'center'
              width="200">
            </el-table-column>
            <el-table-column
              property="disableState"
              align = 'center'
              label="状态"
              width="200">
              <template slot-scope="{row,$index}">
                <span v-if="row.disableState==0">有效可用</span>
                <span v-else-if="row.disableState==1">无效禁用</span>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
    </div>
    <el-dialog title="角色信息维护" :visible.sync="dialogVisible" width="700px" v-dialogDrag   border>
      <el-form :model="saveData.role" ref="roledialog" :rules="rules"  :inline="true" label-width="120px" :disabled="saveFlag">
        <el-row :gutter="5">
          <el-form-item label="业务系统:">
            <el-input v-model="saveData.role.businessSystemName" style="width:515px;" disabled></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="角色编码:" prop="roleCode" >
            <el-input v-model="saveData.role.roleCode" style="width:515px;" :maxlength="20"></el-input>
          </el-form-item>
        </el-row>

        <el-row :gutter="5">
          <el-form-item label="角色名称:" prop="roleName">
            <el-input v-model="saveData.role.roleName" style="width:515px;" :maxlength="20"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="角色分类:" prop="roleTypeCode">
            <el-select v-model="saveData.role.roleTypeCode" style="width:515px;" placeholder="请选择"  :maxlength="50">
              <el-option
                v-for="item in saveData.dicts.role_type"
                :key="item.dataCode"
                :label="item.dataText"
                :value="item.dataCode"
                :disabled="item.disableState?true:false"/>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="状态:"  >
            <el-select v-model="saveData.role.disableState" onkeydown="return (event.keyCode!=8)" style="width:515px;" placeholder="请选择"  :maxlength="50">
              <el-option
                v-for="item in disableState"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="排序:" >
            <el-input  onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null" v-model="saveData.role.sort" style="width:515px;" :maxlength="20"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="备注:">
            <el-input type="textarea" style="width:515px;" v-model="saveData.role.remark"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" v-if="btnRight.btnRoleMngSave" @click="Save()" :disabled="saveFlag">保存</el-button>
        <el-button   v-if="btnRight.btnRoleMngCancel"  @click="cancelForm()">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as API from '@/api/stystemManagement'
  export default {
    name: "roleMng",
    data(){
      return{
        rules: {
          roleCode: [{required: true, message: '请输入角色编码', trigger: 'blur'}],
          roleName: [{required: true, message: '请输入角色名称', trigger: 'blur'}],
          roleTypeCode: [{required: true, message: '请选择角色分类', trigger: 'change'}],
        },
        treeData: [{
          label: '殡葬业务平台',
          id:0,
          children: []
        }],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        tableData: [],
        //禁用状态
        disableState:[
          {label:"有效可用",value:0},{label:"无效禁用",value:1},
        ],
        searchData:{
          "roleName": "",
          "roleTypeCode": "-1",
          "disableState": "-1"
        },
        multipleSelection:[],
        tableSelection:[],
        saveFlag:false, //保存标志
        onpresscTime:0,  //  阻止短时间内连续点击
        dialogVisible:false,  //维护对话框
        saveData:{
          "role": {
            "id": 0,
            "businessSystemId": 0,
            "businessSystemName": 0,
            "roleCode": "string",
            "roleName": "string",
            "roleTypeCode": "string",
            "disableState": 0,
            "remark": "string",
            "sort": 0,
            "version": 0
          },
          "dicts": {
            "role_type": [

            ]
          }
        },btnRight: {
          btnRoleMngAdd: true, //添加
          btnRoleMngEdit: true,//修改
          btnRoleMngDelete: true,//删除
          btnRoleMngSave: true,//保存
          btnRoleMngCancel: true,//取消
          btnRoleMngRefresh: true,//刷新
          btnRoleMngSearch: true,//读取卡号
        }
      }
    },
    mounted(){
      this.loadBusinessSystemListData()
      this.loadRoleWithIdData(0)
      //载入按钮
      this.btnRight = this.$route.meta.buttons;
      //遍历属性赋值将true与false字符串转换成布尔型的值
      for (let key of Object.keys(this.btnRight)) {
        this.btnRight[key]=(this.btnRight[key]|| this.btnRight[key]=="true")?true:false;
      }
    },
    methods: {
      //tree单选
      handleClick(data,checked, node){
        if(checked && data.label!="殡葬业务平台"){
          this.$refs.roleMngTree.setCheckedNodes([data]);
          this.searchData={
            "roleName": "",
            "roleTypeCode": "-1",
            "disableState": "-1"
          }
          this.loadRoleListWithBusinessSystemIdData(data.id)
        }
      },
      //点击行触发，选中或不选中复选框
      handleRowClick(row, column, event) {
        if (this.tableSelection.length>0){
          this.$refs.roleTable.toggleRowSelection(this.tableSelection[0],false);
        }
        this.$refs.roleTable.toggleRowSelection(row);
        this.tableSelection = [row]
      },
      select(selection, row) {
        // 选择项大于1时
        if (selection.length > 1) {
          let del_row = selection.shift();
          // console.log('把数组的第一个元素从其中删除后', selection);
          this.$refs.roleTable.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
        }
        this.tableSelection = selection
      },
      selectAll(selection) {
        if (selection.length >1) {
          selection.length = 1;
        }
        this.tableSelection = selection
      },

      //table中类型添加
      add(){
        let data = this.$refs.roleMngTree.getCheckedNodes()

        if (data.length == 0){
          this.$message("未选中业务系统")
          return
        }else{
          this.saveData.role = {
            "id": 0,
            "businessSystemId": 0,
            "businessSystemName": 0,
            "roleCode": "",
            "roleName": "",
            "roleType": "",
            "disableState": 0,
            "remark": "",
            "sort": 0,
            "version": 0
          }
          this.saveData.role.businessSystemId = data[0].id;
          this.saveData.role.businessSystemName = data[0].label
          this.dialogVisible = true
        }
      },
      modify(){
        //

        let data = this.$refs.roleTable.selection


        if (data && data.length){
          this.loadRoleWithIdData(data[0].id).then( res => {
            if (res) {
              // bug- 154 后端 系统权限管理--角色管理，系统角色应不允许进行修改操作
              console.log(res.dicts.role_type,111);
              let  roleTypes = res.dicts.role_type;
              if (roleTypes.length< 0 || (roleTypes.length == 1 && roleTypes[0].dataCode ==1)){
                this.$message("系统角色无法修改");
                return;
              }
              if (res.role) {
                this.saveData.role = res.role
              }
              let ststem = this.$refs.roleMngTree.getCheckedNodes();
              this.saveData.role.businessSystemId = ststem[0].id;
              this.saveData.role.businessSystemName = ststem[0].label
              this.dialogVisible = true
            }
            else{
              this.$message("数据加载失败")
            }
            this.dialogVisible = true
          })
        } else{
          this.$message("请选择菜单")
          return
        }
      },
      //table中删除
      remove(){
        let ststem = this.$refs.roleMngTree.getCheckedNodes();
        let data = this.tableSelection
        if (ststem.length == 0 || data.length == 0) {
          this.$message("未选中菜单")
          return
        }
        this.$confirm('删除信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let postData = []
          data.forEach(item => {
            postData.push({
              "id": item.id,
              "version": item.version
            })
          })
          API['deleteRoleWithId'](postData).then(response => {
            const {message} = response;
            this.$message(message)
            this.tableSelection = []
            this.loadRoleListWithBusinessSystemIdData(ststem[0].id)
          }).catch(error => {
            this.$message(error)
          })
        }).catch(() => {
          //几点取消的提示
        });
      },
      //加载系统列表
      loadBusinessSystemListData(){
        API['loadBusinessSystemList']().then(response=>{
          const { data }=response;
          if (!data) {
            this.$message('数据读取失败')
            return
          }
          if (data && data.length) {
            data.forEach(item=>{
              item.label = item.systemName
              this.treeData[0].children.push(item)
            })
          }
        }).catch(error => {
          this.$message(error)
        })
      },
      //根据业务系统id，加载系统下所有角色
      loadRoleListWithBusinessSystemIdData(code){
        let postData={
          "businessSystemId": code,
          "roleName": this.searchData.roleName,
          "roleTypeCode": this.searchData.roleTypeCode,
          "disableState": this.searchData.disableState
        }
        return new Promise(resolve => {
          API['loadRoleListWithBusinessSystemId'](postData).then(response=>{
            const { data }=response;
            if (!data) {
              this.$message('数据读取失败')
              return
            }
            this.tableData = data
            resolve(data)
          }).catch(error => {
            this.$message(error)
          })
        })
      },
      //根据业务系统菜单加载所有菜单
      loadRoleWithIdData(id){
        let postData={
          "id": id,  //业务系统菜单记录id
          "dictTypeCodes": ["role_type"]
        }
        return new Promise(resolve => {
          API['loadRoleWithId'](postData).then(response=>{
            const { data }=response;
            if (!data) {
              this.$message('数据读取失败')
              return
            }
            if (data.role) {
              this.saveData.role = data.role
            }
            if (data.dicts) {
              this.saveData.dicts = data.dicts
            }
            resolve(data)
          }).catch(error => {
            this.$message(error)
          })
        })

      },
      search(){
        let ststem = this.$refs.roleMngTree.getCheckedNodes();
        if (ststem && ststem.length) {
          this.loadRoleListWithBusinessSystemIdData(ststem[0].id)
        } else{
          this.$message("请选择系统")
        }
      },
      //保存
      Save(){
        if ((Date.now() - this.onpresscTime) > 2000) {
          this.onpresscTime = Date.now()
          console.log(Date.now())
        }else{
          return
        }
        this.$refs.roledialog.validate(valid => {
          if (valid) {
            this.saveFlag = true
            let postData = this.saveData.role

            API['saveRole'](postData).then(response => {
              const {message} = response;
              this.$message(message)
              let data = this.$refs.roleMngTree.getCheckedNodes()
              this.loadRoleListWithBusinessSystemIdData(data[0].id)
              this.dialogVisible = false
              this.saveFlag = false
            }).catch(error => {
              this.$message(error)
              this.saveFlag = false
            })
          }
        })
      },
      //取消
      cancelForm(){
        this.saveData.role={};
        this.dialogVisible = false
      },
      //验证整数
      onlySortNumber(){
        // 先把非数字的都替换掉，除了数字和.
        let obj=this.saveData.role.sort;
        obj=Number.parseInt(obj);
        this.saveData.role.sort=obj;
      }

    },
    watch:{
      'dialogVisible'(){
        if (this.dialogVisible == false) {
          this.saveData.role={};
          this.$nextTick(()=>{
            this.$refs.roledialog.resetFields();
          })
        }
      }
    }
  }
</script>

<style scoped>
  .tablestyle{
    width: 100%;
    height: calc(100% - 128px);
    overflow-y: scroll;
  }
  @media screen and (max-width: 768px){ /*当屏幕尺寸小于600px时，应用下面的CSS样式*/
    .tablestyle {
      height: calc(100% - 310px);
    }
  }
  @media screen and (min-width: 769px) and (max-width: 1263px){ /*当屏幕尺寸小于600px时，应用下面的CSS样式*/
    .tablestyle {
      height: calc(100% - 190px);
    }
  }
  @media screen and (min-width: 1264px){ /*当屏幕尺寸小于600px时，应用下面的CSS样式*/
    .tablestyle {
      height: calc(100% - 128px);
    }
  }

</style>
